$(function () {
    /*树形组件*/
    layui.use(['tree', 'table', 'util', 'form'], function () {
        var tree = layui.tree
            , layer = layui.layer
            , util = layui.util
            , table = layui.table
            , form = layui.form;
        var depnos = [];
        /*请求获取部门列表*/
        $.ajax({
            url: '/gzht/department/getAll',
            success: function (res) {
                var deps = res || [];
                var data = deps.map(function(item) {
                    return {
                        title: item.departmentName,
                        id: item.departmentNo,
                        pid: item.departmentParentNo,
                        disabled: item.departmentStatus == 1 ? true : false
                    }
                });
                var depTree = trans_tree(data);
                tree.render({
                    elem: '#department' //默认是点击节点可进行收缩
                    , data: depTree
                    , onlyIconControl: true,
                    click: function(obj){
                        // 获取所有末节点机构编号
                        depnos = [];
                        var departmentNos = [];
                        var curData = obj.data; // 当前点击节点数据
                        if(obj.data.children){
                            // 存在子节点
                            var child = obj.data.children;
                            getEndPoint(child, departmentNos);
                        }else {
                            departmentNos.push(curData);
                        }
                        for(var i=0;i<departmentNos.length;i++){
                            depnos.push(departmentNos[i].id)
                        }
                        depnos.push(curData.id)
                        // 更新列表数据
                        if(depnos.length > 0){
                            table.reload('userList', {
                                where: {
                                    departmentNos: depnos.join(','),
                                    adminLoginName: null,
                                    adminPhone: null,
                                    adminStatus: null
                                }
                                ,page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                            });
                        }
                    }
                });
            },
            fail: function () {
                layer.msg("网络出错")
            }
        })
        table.render({
            elem: '#userList'
            , height: 'full-125'
            , skin: 'line'
            , url: '/gzht/api/getAdminList'
            , text: {
                none: '暂无相关数据'
            }
            , title: '用户列表'
            , page: true
            , limits: [5, 10, 20]
            , where: {}
            , toolbar: '#tools'
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {field: 'adminNo', title: '编号', fixed: 'left', hide: true}
                , {field: 'adminLoginName', title: '登录名称'}
                , {field: 'adminName', title: '用户名称', templet: function (d) {
                    var adminNo = $('#adminNo').val()
                    if(d.adminNo == adminNo){
                        return '<span class="layui-badge">'+d.adminName+'</span>'
                    }else {
                        return d.adminName
                    }
                    }}
                , {
                    field: 'department', title: '部门', templet: function (d) {
                        if(d.department){
                            return d.department.departmentName;
                        }else{
                            return '暂无'
                        }
                    }
                }
                , {field: 'adminPhone', title: '手机'}
                , {field: 'adminStatus', title: '用户状态', toolbar: '#switch'}
                , {field: 'adminCreateTime', title: '创建时间'}
                , {fixed: 'right', width: 165, align: 'center', toolbar: '#row_tools'}
            ]]
            , response: {
                statusName: 'code'
                , statusCode: 200
                , msgName: 'msg'
                , countName: 'count'
                , dataName: 'data'
            }
            , parseData: function (res) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.count, //解析数据长度
                    "data": res.data //解析数据列表
                };
            }
        });

        // 监听头部工具条
        table.on('toolbar(userListTable)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var dataLen = checkStatus.data.length;
            switch (obj.event) {
                case 'h_del':
                    if (dataLen == 0) {
                        layer.msg("请选择需要删除的行")
                    } else {
                        layer.confirm('确定删除?', {icon: 3, title:'提示'},function (){
                            console.log("ok");
                            var delAdminNo = [];
                            for(var idx in checkStatus.data){
                                delAdminNo.push(checkStatus.data[idx].adminNo)
                            }
                            $.ajax({
                                url: '/gzht/api/delAdmin',
                                type: 'post',
                                data: {
                                    adminNos: delAdminNo
                                },
                                success: function (res) {
                                    if(res.code == 1001){
                                        layer.msg('删除成功');
                                        table.reload('userList')
                                    }
                                }
                            })
                        })
                    }
                    break;
                case 'h_edit':
                    if (dataLen == 0) {
                        layer.msg("请选择需要编辑的行")
                    } else if (dataLen > 1) {
                        layer.msg("不能同时编辑多个行")
                    } else {
                        var checked = table.checkStatus('userList');
                        console.log(checked)
                        window.location.href = '/gzht/userEdit?adminNo=' + checked.data[0].adminNo
                    }
                    break;
            }
            ;
        });

        //监听行内工具条
        table.on('tool(userListTable)', function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event;
            var tr = obj.tr;

            if (layEvent === 'reset') { //重置
                // 重置密码
                layer.prompt({
                    formType: 1,
                    value: '',
                    title: '重置密码',
                }, function(value, index, elem){
                    if(/^[\S]{6,12}$/.test(value)){
                        $.ajax({
                            url: '/gzht/api/updatePwd',
                            data:{
                                adminPwd: value,
                                adminNo: data.adminNo,
                                adminLoginName: data.adminLoginName
                            },
                            type:'post',
                            success: function (res) {
                                layer.msg(res.desc)
                            }
                        })
                        layer.close(index);
                    }else {
                        layer.msg('密码必须6到12位，且不能出现空格')
                    }
                });
            } else if (layEvent === 'del') { //删除
                layer.confirm('真的删除行么', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                    $.ajax({
                        url: '/gzht/api/delAdmin',
                        type: 'post',
                        data: {
                            adminNos: delAdminNo
                        },
                        success: function (res) {
                            if(res.code == 1001){
                                layer.msg('删除成功');
                                table.reload('userList')
                            }
                        }
                    })
                });
            } else if (layEvent === 'edit') { //编辑
                window.location.href = "/gzht/userEdit?adminNo=" + obj.data.adminNo;
                //同步更新缓存对应的值
                obj.update({
                    userName: '123'
                    , title: 'xxx'
                });
            }
        });
        form.on('switch(switchStatus)', function (obj) {
            layer.tips((this.checked ? '启用' : '禁用') + '用户成功', obj.othis)
        })

        // 监听搜索框
        $('#search').click(function () {
            var formData = new FormData($('#searchForm')[0])
            table.reload('userList', {
                where: {
                    departmentNos: null,
                    adminLoginName: formData.get("adminLoginName"),
                    adminPhone: formData.get("adminPhone"),
                    adminStatus: formData.get("adminStatus")
                }
                ,page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        });
        // 监听搜索重置
        $('#search_reset').click(function () {
            $('#searchForm')[0].reset()
        })
    });
})
